<template>
  <div>
    <SettingTitle ref="settingTitleRef" :titlePlaceholder="$t('projectManage.taskType.new.typeTip')" :templateName="currentTemplateName" :templateColor="color" @handleChangeColor="changeColor" @handleInputTemplateName="inputTemplateName" @submit="handleSubmit" @back="handleBack" />

    <!-- 表单设计器 S -->
    <div class="task-form-design">
      <form-design ref="formDesign" v-model="fields" mode="projectTask" :max="1000"></form-design>
    </div>
    <!-- 表单设计器 E -->
  </div>
</template>
<script>
import { onMounted, reactive, toRefs, computed, ref } from 'vue';

import SettingTitle from '@src/modules/setting/projectManage/components/SettingTitle.vue';

import { getProjectTypeField, saveProjectTypeField, getProjectTypeName } from '@src/api/ProjectManage.ts';
import * as FormUtil from '@src/component/form/util';
import * as FormUtilValidate from '@src/mform/util/validate';

import i18n from '@src/locales';

import { openAccurateTab, toast, notification } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';

import platform from '@src/platform';
export default {
  name: 'project-task-index',
  components: {
    SettingTitle,
  },
  setup() {
    const settingTitleRef = ref();

    const state = reactive({
      init: false,
      currentTemplateName: '',
      color: 'rgb(38,111,255)',
      fields: [],
    });

    // 获取路由参数
    const getParams = computed(() => {
      const searchParams = new URLSearchParams(location.search);
      const params = Object.fromEntries(searchParams.entries());
      return params;
    });

    // 获取模板id
    const getTemplateId = computed(() => {
      return getParams.value?.templateId || '';
    });

    const changeColor = newColor => {
      state.color = newColor;
    };

    const inputTemplateName = val => {
      state.currentTemplateName = val;
    };

    // 获取名称&颜色
    const fetchProjectTypeName = () => {
      getProjectTypeName({
        typeId: getTemplateId.value,
        tableName: 'mission',
      }).then(res => {
        const { success, message, data } = res;

        if (!success) return toast(message, 'error');

        state.currentTemplateName = data.name;
        state.color = data.color;
      });
    };

    // 获取表单字段
    const fetchFormFields = async () => {
      try {
        let ret = await getProjectTypeField({
          templateId: getTemplateId.value,
          tableName: 'mission',
        });

        const { success, data } = ret;
        if (!success) return toast(message, 'error');

        state.fields = FormUtil.toFormField(data);
      } catch (err) {
        console.log('error => fetchFields', err);
      }
    };

    /**
     * 校验表单名称
     */
    const checkFormName = () => {
      if (state.currentTemplateName.length == 0 || state.currentTemplateName === '' || state.currentTemplateName.trim().length == 0) {
        toast(i18n.t('projectManage.taskType.new.typeTip'), 'error');
        return false;
      }
      return true;
    };

    // 将字段转换成后端可接收的字段
    const packToField = origin => {
      let fields = FormUtil.toField(origin);

      fields = (fields || []).map((item, index) => {
        return {
          ...item,
          tableName: 'mission',
          orderId: index,
          // 计划开始结束时间 yyyy-MM-dd
          setting: item.fieldName === 'planStartTime' || item.fieldName === 'planEndTime' ? { dateType: 'date' } : item.setting,
        }
      });

      return fields;
    };

    // 提交表单
    const submitField = async () => {
      try {
        const allFields = packToField(state.fields);

        // 表单字段格式校验
        let checkMessage = FormUtil.validate(allFields);
        if (!FormUtilValidate.notification(checkMessage)) return;

        settingTitleRef.value.pending = true;

        let ret = await saveProjectTypeField({
          templateId: getTemplateId.value,
          mouldName: 'mission',
          name: state.currentTemplateName,
          color: state.color,
          forms: allFields,
        });

        const { success, message } = ret;
        if (!success) {
          return toast(message, 'error');
        } else {
          notification({
            title: i18n.t('common.base.saveSuccess'),
            type: 'success',
          });
          fetchFormFields();
        }
      } catch (err) {
        console.log('error => submitField', err);
      } finally {
        settingTitleRef.value.pending = false;
      }
    };

    // 提交
    const handleSubmit = () => {
      if (!checkFormName()) return;

      submitField();
    };

    // 返回
    const handleBack = () => {
      let fromId = window.frameElement?.getAttribute('id');

      // 关闭当前tab
      let id = window?.frameElement?.dataset?.id;
      platform.closeTab(id);

      openAccurateTab({
        type: PageRoutesTypeEnum.PageProjectManageTaskCartList,
        close: true,
        reload: true,
        fromId,
      });
    };

    onMounted(() => {
      fetchProjectTypeName();
      fetchFormFields();
    });

    return {
      settingTitleRef,
      ...toRefs(state),
      changeColor,
      inputTemplateName,
      handleSubmit,
      handleBack,
    };
  },
};
</script>
<style lang="scss" scoped>
.task-form-design {
  height: calc(100vh - 48px);
  padding: 12px;
}
</style>